package com.cn.transfer.controller;


import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.cn.transfer.common.constant.KeyConstant;
import com.cn.transfer.common.entity.jiandaoyun.JdyPurchaseOrder;
import com.cn.transfer.common.entity.jiandaoyun.Mx;
import com.cn.transfer.common.http.ApiClient;
import com.cn.transfer.common.utils.ConnmeUtils;
import com.cn.transfer.common.vo.UploadToken;
import com.cn.transfer.handle.impl.purchase.community.PurchaseCommunity;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author: 向伟典
 * @date: 2023/9/21 16:49
 * @Description: 上传图片到简道云
 */
@Slf4j
@RestController
public class UploadImageContriler {

    //    private static final String IMAGE_DIRECTORY = "F:/合集/22/";
    //private static final String IMAGE_DIRECTORY = "F:/合集/h/";
//    private static final String IMAGE_DIRECTORY = "F:/合集/AP/";
//    private static final String IMAGE_DIRECTORY = "F:/合集/go/";
    private static final String IMAGE_DIRECTORY = "D:/合集更新/";

    @GetMapping("/uploadJianDaoYun")
    public void uploadJianDaoYun() {
        Map<String, List<UploadToken>> reust = new HashMap<>();
        // 获取指定目录下的所有图片文件
        File imageFolder = new File(IMAGE_DIRECTORY);
        File[] imageFiles = imageFolder.listFiles((dir, name) -> name.endsWith(".jpg") || name.endsWith(".PDF")); // 可根据需要修改文件类型过滤条件

        if (imageFiles != null) {
            for (File imageFile : imageFiles) {
                try {
                    // 从文件创建 MockMultipartFile 对象
                    FileItem fileItem = this.getMultipartFile(imageFile, imageFile.getName());
                    MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
                    // 将图片文件以form-data形式上传到后端
                    // 这里你可以调用你的业务逻辑来处理multipartFile，将其保存或进行其他操作
                    // 这里的示例只是将图片名称作为key，文件内容作为value放入响应Map中

                    int lastDotIndex = imageFile.getName().lastIndexOf(".");

                    String extension = imageFile.getName().substring(0, lastDotIndex);

                    UploadToken uploadToken = new UploadToken();
                    uploadToken.setImgName(imageFile.getName());
                    uploadToken.setImgFile(multipartFile.getBytes());

                    if (reust.containsKey(extension)) {
                        reust.get(extension).add(uploadToken);
                    } else {
                        List<UploadToken> tokenList = new ArrayList<>();
                        tokenList.add(uploadToken);
                        reust.put(extension, tokenList);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        // 简道云传入的图片之后的key和名称

        Header[] headers = ConnmeUtils.createHeaders();
        final int batchSize = 100;  // 每批处理的数据量
        int total = 0;
        int count = 0;
        List<UploadToken> uploadTokensList = new ArrayList<>();
        for (Map.Entry<String, List<UploadToken>> entry : reust.entrySet()) {
            if (count == total) {
                total += batchSize;
                Map<String, Object> parameters = new HashMap<>();
                parameters.put("app_id", "64ee9c37ee0a2c0007bc7afc");
                parameters.put("entry_id", "650ab93189d8223244d5b4cc");
                String s = IdUtil.randomUUID();
                parameters.put("transaction_id", s);
                String jsonSaleDelete = JSONUtil.toJsonStr(parameters);
                JSONObject jdySaledelete = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/file/get_upload_token", headers, jsonSaleDelete);
                String tokenList = jdySaledelete.getStr("token_and_url_list");
                JSONArray objects = JSONUtil.parseArray(tokenList);
                List<UploadToken> uploadTokens = JSONUtil.toList(objects, UploadToken.class);
                for (UploadToken uploadToken : uploadTokens) {
                    uploadToken.setTransactionId(s);
                }
                uploadTokensList.addAll(uploadTokens);
            }
            List<UploadToken> responseMap = new ArrayList<>();
            for (UploadToken uploadToken : entry.getValue()) {
                Header[] headersf = new Header[2];
                headersf[0] = new BasicHeader("Authorization", "Bearer " + KeyConstant.JDY_KEY);
                headersf[1] = new BasicHeader("Content-Type", "multipart/form-data");
                HttpRequest post = HttpRequest.post(uploadTokensList.get(count).getUrl());
                for (Header header : headersf) {
                    post.header(header.getName(), header.getValue());
                }
                String execute = post
                        .form("token", uploadTokensList.get(count).getToken()) // 添加字符串参数
                        .form("file", uploadToken.getImgFile(), uploadToken.getImgName()) // 添加文件参数
                        .execute()
                        .body();

                JSONObject entries = JSONUtil.parseObj(execute);
                UploadToken uploadTokens = new UploadToken();
                uploadTokens.setTransactionId(uploadTokensList.get(count).getTransactionId());
                uploadTokens.setKey(entries.getStr("key"));
                int lastDotIndex =uploadToken.getImgName().lastIndexOf(".");
                String extension = uploadToken.getImgName().substring(0, lastDotIndex);;
                uploadTokens.setImgName(extension);
                responseMap.add(uploadTokens);
                count++;
            }
            String originalFileName = responseMap.get(0).getImgName();
            Map<String, Object> parameter = new HashMap<>();
            parameter.put("app_id", "64ee9c37ee0a2c0007bc7afc");
            parameter.put("entry_id", "650ab93189d8223244d5b4cc");
            List<JdyPurchaseOrder> jdyPurchaseOrders = PurchaseCommunity.queryBased(parameter, headers, originalFileName, "imgname");
            if (jdyPurchaseOrders.size() > 0) {
                Map<String, Object> parameterInster = new HashMap<>();
                parameterInster.put("app_id", "64ee9c37ee0a2c0007bc7afc");
                parameterInster.put("entry_id", "650ab93189d8223244d5b4cc");
                parameterInster.put("data_id", jdyPurchaseOrders.get(0).get_id());
                parameterInster.put("transaction_id", responseMap.get(0).getTransactionId());
                List<String> keys = new ArrayList<>();
                List<UploadToken> first10Elements;
                if (responseMap.size() >= 10) {
                    first10Elements = responseMap.subList(0, 10);
                } else {
                    first10Elements = responseMap; // 如果元素不足10个，将整个列表赋值给 first10Elements
                }
                for (UploadToken uploadToken : first10Elements) {
                    keys.add(uploadToken.getKey());
                }
                Map<String, Object> detailMap = new HashMap<>();
                Map<String, Object> appendixs = new HashMap<>();
                appendixs.put("value", keys);
                detailMap.put("appendix", appendixs);

                Map<String, Object> imgnames = new HashMap<>();
                imgnames.put("value", originalFileName);
                detailMap.put("imgnames", imgnames);
                Map<String, Object> id = new HashMap<>();
                id.put("value", jdyPurchaseOrders.get(0).getMx().get(0).get_id());
                detailMap.put("_id", id);
                List<Map<String, Object>> mapList = new ArrayList<>();
                mapList.add(detailMap);
                Map<String, Object> mxs = new HashMap<>();
                mxs.put("value", mapList);
                Map<String, Object> mxse = new HashMap<>();
                mxse.put("mx", mxs);
                parameterInster.put("data", mxse);
                String jsonSale = JSONUtil.toJsonStr(parameterInster);
                log.info("当前正在修改附件发送给简道云的数据：==== " + jsonSale);
                JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSale);
                log.info("修改的数据===" + jdySale);
            }
        }

    }

    private FileItem getMultipartFile(File file, String fieldName) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem(fieldName, "text/plain", true, file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }


}
